<?php

namespace Common\Logic;

/**
 * Description of AccountLogic.class控制器实例
 *
 * @author songanwei
 * @date 2016-1-4
 */
class AccountLogic extends \Common\Controller\BaseController {

    /**
     * 根据客栈ID获取子管理员信息
     * @modity trainyao 2016-07-26 逻辑重构
     * @param integer             $userId           超级管理员ID
     * @return array 传入客栈的子管理员信息数组  [{id,name,mobile,groupId,hotels(子管理员有权限的客栈)}, {}, ...]
     */
    public function getSub($userId) {
        return $this->__singleGet('_getSub', array($userId));
    }
    protected function _getSub($userId) {
        $adminHotelModel = D('AdminHotel');
        $hotelIds = $adminHotelModel->getInfosByAdmin($userId);
        if (empty($hotelIds)) {
            return array();
        }

        // 获取子管理员客栈关系
        $hotelIds = array_column($hotelIds, 'hotelentity_id');
        $adminHotelModel = D('AdminHotel');
        $adminHotels = $adminHotelModel->getInfosByHotel($hotelIds);
        $adminHotels = getArrayValueAsIndex($adminHotels, 'adminlogin_id', 'multi');

        // 获取超级管理员所操作的组-子管理员关系
        $userId = getUserId();
        $groupLogic = A('Common/Group', 'Logic');
        $groupId = $groupLogic->getInfoByUser($userId);
        $groupId = array_column($groupId, 'id');
        $groupAdminModel = D('GroupAdmin');
        $adminGroupRelation = $groupAdminModel->getInfoByGroup($groupId);
        $adminGroupRelation = getArrayValueAsIndex($adminGroupRelation, 'adminlogin_id');
        // 获取子管理员详细信息
        $adminLoginModel = D('AdminLogin');
        $adminIds = array_keys($adminHotels);
        $adminLoginInfo = $adminLoginModel->getInfo($adminIds);
        if (count($adminIds) == 1) {
            $adminLoginInfo = array($adminLoginInfo);
        }
        $adminLoginInfo = getArrayValueAsIndex($adminLoginInfo, 'id');

        // 整理数据返回 查询客栈数据
        foreach ($adminHotels as $adminLoginId => &$adminItem) {
            $adminItem = array(
                'id' => $adminLoginId,
                'name' => $adminLoginInfo[$adminLoginId]['name'],
                'mobile' => $adminLoginInfo[$adminLoginId]['mobile'],
                'areacode' => $adminLoginInfo[$adminLoginId]['areacode'],
                'groupId' => empty($adminGroupRelation[$adminLoginId]) ? 0 : $adminGroupRelation[$adminLoginId]['groupinfo_id'],
                'hotels' => array_column($adminItem, 'hotelentity_id'),
            );
        }
        unset($adminItem);

        return array_values($adminHotels);
    }

    /**
     * 添加客栈管理账号
     * @modify songanwei 2016-01-04
     * @modify wenhui 2017-05-24  新增区号
     * @param type $adminId   管理员ID
     * @param type $account 账号
     * @param type $accountName  账号名称
     * @param type $areaCode  区号
     */
    public function addSub($adminId, $account, $accountName, $areaCode = '86') {
        //查询管理客栈
        $adminHotelModel = D('AdminHotel');
        $adminHotels = $adminHotelModel->getInfosByAdmin($adminId);
        if (empty($adminHotels)) {
            returnJson(403, 202);
        }
        //获取客栈ID
        $hotelIds = array_column($adminHotels, "hotelentity_id");

        //获取客栈默认权限
        $hotelAuthorityModel = D('HotelAuthority');
        $defaultAuthoritys = $hotelAuthorityModel->getInfosByDefault();

        $adminAuthorityData = $adminHotelData = array();
        //检查账户是否已添加
        $adminLoginModel = D('AdminLogin');
        $adminLogin = $adminLoginModel->getInfoByMobile($account, $areaCode);

        if ($adminLogin) {
            //检查用户是否已存在
            $result = $adminHotelModel->checkExistAdmin($adminLogin['id'], $hotelIds);
            if ($result) {
                //账号已存在
                returnJson(403, 104);
            }
        }

        //开启事务处理
        $adminHotelModel->startTrans();
        $commit = true;

        //未注册用户
        if ($adminLogin) {
            foreach ($hotelIds as $hotelId) {
                $adminHotelData[] = array(
                    'hotelentity_id' => $hotelId,
                    'adminlogin_id' => $adminLogin['id'],
                    'role' => 2
                );
                foreach ($defaultAuthoritys as $defaultAuthority) {
                    $adminAuthorityData[] = array(
                        'adminlogin_id' => $adminLogin['id'],
                        'hotelentity_id' => $hotelId,
                        'hotelauthority_id' => $defaultAuthority['id'],
                        'creator' => getUserId()
                    );
                }
            }
        } else {
            $token = getRandomPassword();
            // 添加用户主表
            $result = $adminLoginId = $adminLoginModel->addInfo($account, hash('sha256', $token), $accountName, $areaCode);
            if ($result == false) {
                $commit = false;
            }
            //添加用户从表
            $adminInfoModel = D('AdminInfo');
            if ($commit) {
                $result = $adminInfoModel->addInfo($adminLoginId);
                if ($result == false) {
                    $commit = false;
                }
            }

            foreach ($hotelIds as $hotelId) {
                $adminHotelData[] = array(
                    'hotelentity_id' => $hotelId,
                    'adminlogin_id' => $adminLoginId,
                    'role' => 2
                );
                foreach ($defaultAuthoritys as $defaultAuthority) {
                    $adminAuthorityData[] = array(
                        'adminlogin_id' => $adminLoginId,
                        'hotelentity_id' => $hotelId,
                        'hotelauthority_id' => $defaultAuthority['id'],
                        'creator' => getUserId()
                    );
                }
            }
        }

        //添加管理员客栈关系数据
        if ($commit && $adminHotelData) {
            $result = $adminHotelModel->addAll($adminHotelData);
            if ($result == false) {
                $commit = false;
            }
        }

        //添加管理员客栈默认权限
        $adminAuthorityModel = D('AdminAuthority');
        if ($commit && $adminAuthorityData) {
            $result = $adminAuthorityModel->addAll($adminAuthorityData);
            if ($result == false) {
                $commit = false;
            }
        }

        //事务提交
        if ($commit) {
            $adminHotelModel->commit();
            //发送短信通知
            if (!$adminLogin) {  
                if ($areaCode == '86') {
                    $sms = new \Org\Util\Sms();
                    $result = $sms->sendNotReg($account, $token);
                } else {
                    $sms = new \Org\Util\yunPian();
                    $result = $sms->sendNotReg($areaCode, $account, $token);
                }

                if ($result == false) {
                    returnJson(403, 151);
                }
            }
        } else {
            $adminHotelModel->rollback();
            returnJson(500, 508);
        }
    }

    /**
     * 删除子账号
     * @modify songanwei 2016-01-04
     * @param integer $adminId  客栈创建管理员ID
     * @param integer $userId  客栈管理员ID
     */
    public function deleteSub($adminId, $userId) {
        //检查管理账号权限
        $adminHotelModel = D('AdminHotel');
        $adminHotels = $adminHotelModel->getInfosByAdmin($adminId);
        if (empty($adminHotels)) {
            returnJson(403, 324);
        }
        //获取所有的客栈ID

        $hotelIds = array_column($adminHotels, "hotelentity_id");

        $adminHotelModel->startTrans();
        $commit = true;
        //删除管理客栈关系
        $result = $adminHotelModel->deleteInfoAdminHotel($userId, $hotelIds);
        if ($result == false) {
            $commit = false;
        }

        // 删除子管理员的对应客栈房间权限
        if ($commit) {
            $hotelRoomAuthorityModel = D('HotelRoomAuthority');
            $result = $hotelRoomAuthorityModel->deleteInfoByHotel($userId, $hotelIds);
            if (empty($result)) {
                $commit = false;
            }
        }

        //删除管理客栈权限数据
        $adminAuthorityModel = D('AdminAuthority');
        $result = $adminAuthorityModel->deleteInfoByAdminHotel($userId, $hotelIds);
        if ($result == false) {
            $commit = false;
        }

        if ($commit) {
            $adminHotelModel->commit();
        } else {
            $adminHotelModel->rollback();
            returnJson(500, 510);
        }
    }

    /**
     * 设置权限||检查数据有效性,检查用户是否在客栈内,查询数据 获取新增数据，删除数据，在更新
     * @modify songanwei 2016-01-04
     * @param integer $adminId 客栈创建管理员ID
     * @param integer $accountId 客栈管理账号ID
     * @param array $authorities   array(0=>array('hotelId'=>'1','authorityStr'=>'1,2,3,4,5'),1=>array())
     */
    public function setAuthority($adminId, $accountId, $authorities, $multiTrans = false) {
        //检查管理账号权限并获取客栈ID数据
        $adminHotelModel = D('AdminHotel');
        $adminHotels = $adminHotelModel->getInfosByAdmin($adminId);
        if (empty($adminHotels)) {
            returnJson(403, 202);
        }
        $hotelIds = array_column($adminHotels, "hotelentity_id");
        //获取用户传入的hotelId,非法返回结果
        $hotelIdsInput = array_column($authorities, "hotelId");
        if (array_diff($hotelIdsInput, $hotelIds)) {
            returnJson(403, 202);
        }
        //检查hotelId是否为后来新增
        for ($k = 0; $k < count($hotelIdsInput); $k++) {
            $result = $adminHotelModel->checkExistAdmin($accountId, $hotelIdsInput[$k]);
            if ($result == false) {
                $hotelIdsAdd[] = $hotelIdsInput[$k];
            }
        }

        //获取权限下删除的客栈数据
        $authorityHotelDelete = array_diff($hotelIds, $hotelIdsInput);
        $hotelAuthorityArrAdd = $hotelAuthorityArrDeleete = array();
        //查询所有数据
        $adminAuthorityModel = D('AdminAuthority');
        $hotelAuthorityModel = D('HotelAuthority');
        $hotelAuthorities = $hotelAuthorityModel->getAll();
        $hotelAuthorityArrAll = array_column($hotelAuthorities, "id");
        //查询数据
        foreach ($authorities as $authority) {
            if ($authority['authorityStr']) {
                $adminAuthorityNew = explode(',', $authority['authorityStr']);
            } else {
                $adminAuthorityNew = array();
            }

            $adminAuthorities = $adminAuthorityModel->getInfosByAdminHotel($accountId, $authority['hotelId']);
            $adminAuthorityExist = array_column($adminAuthorities, "hotelauthority_id");

            $hotelAuthorityArrAdd = array_diff($adminAuthorityNew, $adminAuthorityExist);
            $hotelAuthorityArrDeleete = array_diff($hotelAuthorityArrAll, $adminAuthorityNew);
            $hotelAuthorityArrAdd = array_values($hotelAuthorityArrAdd);
            $hotelAuthorityArrDeleete = array_values($hotelAuthorityArrDeleete);
            for ($i = 0; $i < count($hotelAuthorityArrAdd); $i++) {
                $adminHotelArrAdd[] = array(
                    'adminlogin_id' => $accountId,
                    'hotelentity_id' => $authority['hotelId'],
                    'hotelauthority_id' => $hotelAuthorityArrAdd[$i],
                    'creator' => getUserId()
                );
            }
            for ($j = 0; $j < count($hotelAuthorityArrDeleete); $j++) {
                $adminHotelArrDelete[] = array(
                    'adminlogin_id' => $accountId,
                    'hotelentity_id' => $authority['hotelId'],
                    'hotelauthority_id' => $hotelAuthorityArrDeleete[$j]
                );
            }
        }

        //检查用户是否在客栈内
        if ($multiTrans === false) {
            $adminAuthorityModel->startTrans();
        }
        $commit = true;

        //添加客栈管理员数据
        if ($hotelIdsAdd) {
            $rows = array();
            for ($i = 0; $i < count($hotelIdsAdd); $i++) {
                $rows[] = array(
                    'hotelentity_id' => $hotelIdsAdd[$i],
                    'adminlogin_id' => $accountId,
                    'role' => 2
                );
            }
            $result = $adminHotelModel->addAll($rows);
            if ($result == false) {
                $commit = false;
            }
        }

        //删除用户客栈关系
        $hotelIdToDelete = getArrayValueAsIndex($authorities, 'authorityStr', 'multi');
        $hotelIdToDelete = array_column($hotelIdToDelete[''], 'hotelId');
        if ($commit && !empty($hotelIdToDelete)) {
            $result = $adminHotelModel->deleteInfoAdminHotel($accountId, $hotelIdToDelete);
            if ($result == false) {
                $commit = false;
            }

            // 删除子管理员客栈房间权限
            if ($commit) {
                $hotelRoomAuthorityModel = D('HotelRoomAuthority');
                $result = $hotelRoomAuthorityModel->deleteInfoByHotel($accountId, $hotelIdToDelete);
                if (empty($result)) {
                    $commit = false;
                }
            }
        }

        //新增客栈权限数据
        if ($commit && $adminHotelArrAdd) {
            $result = $adminAuthorityModel->addAll($adminHotelArrAdd);
            if ($result == false) {
                $commit = false;
            }
        }
        //删除原有减少数据
        if ($commit && $adminHotelArrDelete) {
            foreach ($adminHotelArrDelete as $row) {
                $result = $adminAuthorityModel->deleteInfoByAdminHotelAuthority($accountId, $row['hotelentity_id'], $row['hotelauthority_id']);
                if ($result == false) {
                    $commit = false;
                    break;
                }
            }
        }
        //删除不存在的客栈权限数据
        if ($commit && $authorityHotelDelete) {
            foreach ($authorityHotelDelete as $hotelId) {
                $result = $adminAuthorityModel->deleteInfoByAdminHotel($accountId, $hotelId);
                if ($result == false) {
                    $commit = false;
                }
            }
        }

        if ($commit) {
            if ($multiTrans === false) {
                $adminHotelModel->commit();
            }
            return true;
        } else {
            if ($multiTrans === false) {
                $adminHotelModel->rollback();
            }
            returnJson(500, 509);
            return false;
        }
    }

    /**
     * 获取客栈内的所有用户权限
     * @Modify songanwei 2016-01-08
     * @param integer $userId  管理员客栈创建ID
     * @param integer $accountId  管理员ID
     */
    public function getAuthority($userId, $accountId) {
        return $this->__singleGet('_getAuthority', array($userId, $accountId));
    }
    protected function _getAuthority($userId, $accountId) {
        //查询管理客栈
        $adminHotelModel = D('AdminHotel');
        $adminHotels = $adminHotelModel->getInfosByAdmin($userId);
        if (empty($adminHotels)) {
            returnJson(403, 202);
        }
        //获取客栈ID
        $hotelIds = array_column($adminHotels, "hotelentity_id");

        $adminAuthorityModel = D('AdminAuthority');
        $adminAuthoritys = $adminAuthorityModel->getInfosByAdminHotel($accountId, $hotelIds);

        //分k客栈获取用户权限
        $authoritys = $authorityResult = array();
        foreach ($adminAuthoritys as $adminAuthority) {
            $authoritys[$adminAuthority['hotelentity_id']][] = $adminAuthority;
        }
        //转化数据
        foreach ($authoritys as $key => $authority) {
            $authorityResult[] = array(
                'hotelId' => $key,
                'authoritys' => $authority
            );
        }

        return $authorityResult;
    }

    /**
     * 获取子管理员在超级管理员管理客栈下房间权限
     * 方法会抛异常
     * @modify trainyao 2016-06-28 创建
     * @param  integer   $userId    超级管理员ID
     * @param  integer   $accountId 子管理员ID
     * @return array              信息数组 [{hotelentity_id,roomAuthority,name,roomType:[{
     *                                         id, name, room:[{
     *                                                 id, name, roomAuthority
     *                                             }, {},...]
     *                                         }, {},...
     *                                     ]}]
     */
    public function getRoomAuthority($userId, $accountId) {
        //查询管理客栈
        $adminHotelModel = D('AdminHotel');
        $adminHotels = $adminHotelModel->getInfosByAdmin($userId);
        if (empty($adminHotels)) {
            throw new \Exception('403,202', 202);
            return false;
        }
        // 获取客栈ID
        $hotelIds = array_column($adminHotels, 'hotelentity_id');
        $adminAuthorityModel = D('AdminAuthority');
        $adminAuthoritys = $adminAuthorityModel->getInfosByAdminHotel($accountId, $hotelIds);
        $adminAuthoritys = getArrayValueAsIndex($adminAuthoritys, 'hotelentity_id', 'multi');
        // 获取客栈信息
        $hotelLogic = A('Common/Hotel', 'Logic');
        $hotelInfo = $hotelLogic->getHotelByHotelId($hotelIds);
        $hotelInfo = getArrayValueAsIndex($hotelInfo, 'id');

        // 获取管理员房间权限
        $hotelRoomAuthorityModel = D('HotelRoomAuthority');
        $hasRightRoomIds = $hotelRoomAuthorityModel->getInfoByAdminHotel($accountId, $hotelIds);
        $hasRightRoomIds = array_column($hasRightRoomIds, 'roominfo_id');

        // 获取各个酒店的房型房间数据
        $roomTypeLogic = A('Common/RoomType', 'Logic');
        foreach ($adminHotels as &$hotelItem) {
            $hotelItem['name'] = $hotelInfo[$hotelItem['hotelentity_id']]['name'];
            $hotelItem['roomType'] = $roomTypeLogic->getInfoByHotel($hotelItem['hotelentity_id']);
            foreach ($hotelItem['roomType'] as &$roomTypeItem) {
                foreach ($roomTypeItem['room'] as &$roomItem) {
                    $roomItem['roomAuthority'] = DISABLE;
                    if (in_array($roomItem['id'], $hasRightRoomIds)) {
                        $roomItem['roomAuthority'] = ENABLE;
                    }
                }
                unset($roomItem);
            }
            unset($roomTypeItem);
        }
        unset($hotelItem);

        return $adminHotels;
    }

    /**
     * 保存子管理员多个客栈的房间权限
     * 方法会抛异常
     * @modify trainyao 2016-06-28          创建
     * @param  integer   $accountId          子管理员ID
     * @param  array   $hotelRoomAuthority   [{hotel,room=>[0,1,2]}, {}, {},...]
     * @param  mixin   $multiTrans        是否处于事务嵌套,默认否
     * @return boolean  执行结果
     */
    public function saveRoomAuthority($adminId, $accountId, $hotelRoomAuthority, $multiTrans = false) {
        // 获取现有的房间权限
        $roomAuthorityInfo = $this->getRoomAuthority($adminId, $accountId);
        // 生成需要新增,删除的房间权限信息
        $hotelRoomAuthority = getArrayValueAsIndex($hotelRoomAuthority, 'hotel');
        $roomAuthorityToAdd = array();
        $roomAuthorityToDelete = array();
        foreach ($roomAuthorityInfo as $hotelRoomAuthorityItem) {
            // 收集单个客栈具有权限的房间ID
            $roomAuthority = array();
            foreach ($hotelRoomAuthorityItem['roomType'] as $key => $roomTypeAuthorityItem) {
                $roomAuthority = array_merge($roomAuthority, $roomTypeAuthorityItem['room']);
            }
            unset($roomTypeAuthorityItem);
            $roomAuthority = getArrayValueAsIndex($roomAuthority, 'roomAuthority', 'multi');
            $roomAuthority = isset($roomAuthority[ENABLE]) ? $roomAuthority[ENABLE] : array();
            $roomAuthority = array_column($roomAuthority, 'id');

            // 分别需要增加删除权限的房间ID
            foreach (array_diff($hotelRoomAuthority[$hotelRoomAuthorityItem['hotelentity_id']]['room'], $roomAuthority) as $roomId) {
                array_push($roomAuthorityToAdd, array(
                    'hotelentity_id' => $hotelRoomAuthorityItem['hotelentity_id'],
                    'roominfo_id' => $roomId,
                ));
            }
            unset($roomId);
            foreach (array_diff($roomAuthority, $hotelRoomAuthority[$hotelRoomAuthorityItem['hotelentity_id']]['room']) as $roomId) {
                array_push($roomAuthorityToDelete, $roomId);
            }
            unset($roomId);
        }
        unset($hotelRoomAuthorityItem);

        $hotelRoomAuthorityModel = D('HotelRoomAuthority');
        if ($multiTrans === false) {
            $hotelRoomAuthorityModel->startTrans();
        }
        $commit = true;

        if (!empty($roomAuthorityToAdd)) {
            $saveResult = $hotelRoomAuthorityModel->addInfo($accountId, $roomAuthorityToAdd);
            if (empty($saveResult)) {
                $commit = false;
            }
        }

        if ($commit && !empty($roomAuthorityToDelete)) {
            $saveResult = $hotelRoomAuthorityModel->deleteInfoByRoom($accountId, $roomAuthorityToDelete);
            if (empty($saveResult)) {
                $commit = false;
            }
        }

        if (!$commit) {
            if ($multiTrans === false) {
                $hotelRoomAuthorityModel->rollback();
            }
            throw new \Exception('500,506', 506);
            return false;
        }

        if ($multiTrans === false) {
            $hotelRoomAuthorityModel->commit();
        }
        return true;
    }

    /**
     * 获取子管理员某个客栈的房间权限
     * @modify trainyao 2016-06-28 创建
     * @param  integer   $adminId   子管理员ID
     * @param  integer   $hotelId   客栈ID
     * @return array              有权限房间ID
     */
    public function getAdminRoomAuthority($adminId, $hotelId) {
        return $this->__singleGet('_getAdminRoomAuthority', array($adminId, $hotelId));
    }
    protected function _getAdminRoomAuthority($adminId, $hotelId) {
        $hotelRoomAuthorityModel = D('HotelRoomAuthority');
        $hotelRoomAuthorityInfo = $hotelRoomAuthorityModel->getInfoByAdminHotel($adminId, $hotelId);
        return array_column($hotelRoomAuthorityInfo, 'roominfo_id');
    }

    /**
     * 校验是否可以管理子管理员
     * 方法不会抛异常
     * @modify trainyao 2016-07-26    创建
     * @param   integer  $userId  超级管理员ID
     * @param   mixin  $adminLoginId  子管理员ID数组
     * @return boolean   可以管理返回ture,不可管理返回false
     */
    public function checkCanOperate($userId, $adminLoginId) {
        if (!is_array($adminLoginId)) {
            $adminLoginId = explode(',', $adminLoginId);
        }

        // 获取子管理员信息
        $adminInfo = $this->getSub($userId);
        if (empty($adminInfo)) {
            return false;
        }

        return empty(array_diff($adminLoginId, array_column($adminInfo, 'id')));
    }
}
